﻿/* $RCSFile: ProductsDownLoad.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/PageModules/Download/ProductsDownLoad.ascx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:11  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Web.Security;
using System.Xml;
using System.Configuration;

using AddonNice;
using AddonNice.Authentication;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using AddonNice.CRMWrapper.ECommerce;

using AddonNice.CRMImage;
using AddonNice.CRMImage.UI;

using AddonNice.ECommerce;
using AddonNice.ECommerce.Helpers;
using AddonNice.ECommerce.Design;
using AddonNice.ECommerce.UI;
using AddonNice.ECommerce.UI.WebControls;
using AddonNice.Settings.Download;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.Download
{
    public class AStr
    {
        public const string RequireRegistered   =   "PRODDOWNLOAD_REQUIREREGISTERED";
        public const string Transfer2Register   =   "PRODDOWNLOAD_TRANSFER2REGISTER";
    }

    /// <summary>
    /// Initializer class for ProductsDownLoad 
    /// </summary>
    public class ProductsDownLoadSI : PortalCRMModuleControlSI
    {
        public ProductsDownLoadSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ProductsDownLoadSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ProductsDownLoadSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ProductsDownLoadSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                               =   pm.ExtendedResourcesGroup;

			SettingItemSpecial RequireRegistered	    =   new SettingItemSpecial(AStr.RequireRegistered,new BooleanDataType());
			RequireRegistered.Value				        =   StStr.strFalse;
			RequireRegistered.Order				        =   10;
            RequireRegistered.Group                     =   SettingItemGroup.MODULE_SPECIAL_SETTINGS; // necessary to split tabs
            RequireRegistered.ExtendedGroupName         =   extgrp;
            RequireRegistered.ResourceFile              =   EComStStr.ResourceFile;
            RequireRegistered.ResourceItem              =   EComStStr.ResourceItem;
            RequireRegistered.EnglishName			    =   "Require Registered users";
            RequireRegistered.Description			    =   "Allows only registered users to download";
			bSettings.AddSetting(RequireRegistered);

            SettingItemSpecial Transfer2Register	    =   new SettingItemSpecial(AStr.Transfer2Register,new BooleanDataType());
			Transfer2Register.Value				        =   StStr.strFalse;
			Transfer2Register.Order				        =   20;
            Transfer2Register.Group                     =   SettingItemGroup.MODULE_SPECIAL_SETTINGS; // necessary to split tabs
            Transfer2Register.ExtendedGroupName         =   extgrp;
            Transfer2Register.ResourceFile              =   EComStStr.ResourceFile;
            Transfer2Register.ResourceItem              =   EComStStr.ResourceItem;
            Transfer2Register.EnglishName			    =   "Aut transfer to register page";
            Transfer2Register.Description			    =   "When only registered users allowed to download, transfer irectly to register Page";
			bSettings.AddSetting(Transfer2Register);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]ProductsDownLoadSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class ProductsDownLoad : ECommerceModule
    {
        Prod2DownLoadDB dwnDB               =   new Prod2DownLoadDB();

		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid(EComStStr.ProductsDownLoadGuid);
			}
		}

		#endregion Global Implementation
        
        #region Ctor

        /// <summary>
		/// Ctor Set the properties of the module
		/// </summary>
        public ProductsDownLoad()
        {
            if (TraceProducts.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad Ctor enter at: {0}", DateTime.UtcNow), TraceProducts.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                         =   "PRODUCTSDOWNLOAD";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new ProductsDownLoadSI(bSettings,this);
        }

        #endregion Ctor

        protected void Page_Load(object sender, EventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad Page_Load BEG IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if ( ! IsPostBack )
            {
                SqlDataReader dr                        =   null;
                try
                {
                    bool userLgd                        =   UserLogged;
                    if ( userLgd )
                    {
                        AddonNiceMembershipUser user    =   (AddonNiceMembershipUser)Membership.GetUser();
                        // First get products bought by this user
                        dr                              =   dwnDB.GetUserDownLoadByUserId(user.UserId);
                        while( dr.Read() )
                        {
                            int UserDownLoadId          =   (int)dr["UserDownLoadId"];
                            Guid ProductId              =   (Guid)dr["ProductId"];
                            int Prod2DownLoadId         =   (int)dr["Prod2DownLoadId"];
	                        DateTime    StartDate       =   (DateTime)dr["StartDate"];
	                        DateTime    EndDate         =   (DateTime)dr["EndDate"];
                            DateTime curDate            =   DateTime.Now;
		                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad Page_Load found ProductId: {0}, StartDate: {1}, EndDate: {2}",
                                    ProductId,StartDate,EndDate),ModuleTraceSwitch.Sw.Info);
                            if ( StartDate > curDate || EndDate < curDate )
                                continue;
                            ADNDynProduct prod          =    DynEntity.GetFromCache<ADNDynProduct>(CrmStr.product,Wrapper,ResetWrapper,ProductId);
                            if ( !prod.Retrieved )
                                continue;
		                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad Page_Load adding Product.name: {0}",prod.name),ModuleTraceSwitch.Sw.Info);

                            SqlDataReader dr2           =   null;
                            try
                            {
                                dr2                     =   dwnDB.GetProd2DownLoad(Prod2DownLoadId);
                                dr2.Read();
                                string ShortDescription =   (string)dr2["ShortDescription"];
                                RadTreeNode nd          =   new RadTreeNode(ShortDescription,Prod2DownLoadId.ToString());
                                nd.Attributes["UDnId"]  =   UserDownLoadId.ToString();
                                nd.Category             =   "Product";
                                RadTreeView1.Nodes.Add(nd);
                                AddProductNodes(nd,Prod2DownLoadId);
                            }
                            catch(Exception ex)
                            {
                                if (ModuleTraceSwitch.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ProductsDownLoad Page_Load ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                                throw;
                            }
                            finally
                            {
                                if ( dr2 != null )
                                    dr2.Close();
                            }
                        }
                        if ( dr != null )
                            dr.Close();
                    }
                    // then free products available for everybody depending on settings
                    if ( userLgd || !Settings[AStr.RequireRegistered].ToBool() )
                    {
                        dr                                  =   dwnDB.GetAllProd2DownLoadForEverybody();
                        while( dr.Read() )
                        {
                            Guid ProductId                  =   (Guid)dr["ProductId"];
                            int Prod2DownLoadId             =   (int)dr["Prod2DownLoadId"];
		                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad Page_Load found Free ProductId: {0}",ProductId),ModuleTraceSwitch.Sw.Info);
                            ADNDynProduct prod              =    DynEntity.GetFromCache<ADNDynProduct>(CrmStr.product,Wrapper,ResetWrapper,ProductId);
                            if ( !prod.Retrieved )
                                continue;
		                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad Page_Load adding Free Product.name: {0}",prod.name),ModuleTraceSwitch.Sw.Info);
                            SqlDataReader dr2               =   null;
                            try
                            {
                                dr2                         =   dwnDB.GetProd2DownLoad(Prod2DownLoadId);
                                dr2.Read();
                                string ShortDescription     =   (string)dr2["ShortDescription"];
                                RadTreeNode nd              =   new RadTreeNode(ShortDescription,Prod2DownLoadId.ToString());
                                nd.Category                 =   "FreeProduct";
                                nd.Attributes["UDnId"]      =   "-1"; // nobody
                                RadTreeView1.Nodes.Add(nd);
                                AddProductNodes(nd,Prod2DownLoadId);
                            }
                            catch(Exception ex)
                            {
                                if (ModuleTraceSwitch.Sw.TraceError)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ProductsDownLoad Page_Load ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                                throw;
                            }
                            finally
                            {
                                if ( dr2 != null )
                                    dr2.Close();
                            }
                        }
                    }
                    else if ( !userLgd && Settings[AStr.Transfer2Register].ToBool() )
                    {
                        string NavigateUrl                  =   HttpUrlBuilder.BuildUrl("~/register.aspx",true,DynPageLoc.Login,StStr.RegisterPageID);
                        ADNPage.Redirect(NavigateUrl,true);
                    }
                }
                catch(Exception ex)
                {
                    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ProductsDownLoad Page_Load ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
                finally
                {
                    if ( dr != null )
                        dr.Close();
                }
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]ProductsDownLoad Page_Load END.",ModuleTraceSwitch.Sw.Info);
        }

        void AddProductNodes(RadTreeNode nd,int Prod2DownLoadId)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad AddProductNodes BEG Prod2DownLoadId: {0}",Prod2DownLoadId),ModuleTraceSwitch.Sw.Info);
            SqlDataReader dr3               =   null;
            try
            {
                dr3                         =   dwnDB.GetVersionProdByDownloadId(Prod2DownLoadId);
                while(dr3.Read())
                {
                    int VersionProdId       =   (int)dr3["VersionProdId"];
                    string wVersion         =   (string)dr3["Version"];
                    DateTime VersionDate    =   (DateTime)dr3["VersionDate"];
                    string WhatsNew         =   (string)dr3["WhatsNew"];
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad AddProductNodes adding Version: {0}",wVersion),ModuleTraceSwitch.Sw.Info);
                    RadTreeNode ndVersion   =   new RadTreeNode(wVersion,VersionProdId.ToString());
                    ndVersion.Category      =   "Version";
                    // Store Whats new in an attribute of version
                    ndVersion.Attributes["WhatsNew"]    =   WhatsNew;
                    ndVersion.Attributes["VersionDate"] =   VersionDate.ToString("d");

                    nd.Nodes.Add(ndVersion);
                    RadTreeNode nd22        =   new RadTreeNode(VersionDate.ToString("d"));
                    nd22.Category           =   "VersionDate";
                    ndVersion.Nodes.Add(nd22);
                }
                nd.Expanded                 =   true;
            }
            catch(Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ProductsDownLoad AddProductNodes ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if ( dr3 != null )
                    dr3.Close();
            }
        }

        void AddNodeFile(SqlDataReader dr,int UserDownLoadId)
        {
            int VersionFileId       =   (int)dr["VersionFileId"];
            string VersionFileTitle =   (string)dr["VersionFileTitle"];
            double VersionFileSize  =   (double)(int)dr["VersionFileSize"];
            string sz               =   string.Format("{0:F0} bytes",VersionFileSize);
            if ( VersionFileSize > 1024 )
                sz                  =   string.Format("{0:F2} Kb",VersionFileSize/1024);
            if ( VersionFileSize > (1024*1024) )
                sz                  =   string.Format("{0:F2} Mb",VersionFileSize/(1024*1024));
            bool VersionFileIsMain  =   (bool)dr["VersionFileIsMain"];
            string VersionFileName  =   (string)dr["VersionFileName"];
            string txt              =   string.Format("{0} sz: {1} {2}",VersionFileTitle,sz,VersionFileIsMain ? "<b>Main</b>":string.Empty);

            string url              =   string.Format("{0}/Download/downloadgenerator.aspx?VFId={1}&UDwnId={2}&pageid={3}&Mid={4}",
                                                        new object[]{Config.ModulesPath,VersionFileId,UserDownLoadId,PageID,ModuleID});
	        if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad AddNodeFile url: {0}",url),ModuleTraceSwitch.Sw.Info);
            RadTreeNode nd          =   new RadTreeNode(txt,VersionFileId.ToString(),url);
            nd.Target               =   "_blank";
	        if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad AddNodeFile Adding Node: {0}",txt),ModuleTraceSwitch.Sw.Info);
            RadTreeView2.Nodes.Add(nd);
        }
        
        /// <summary>
        /// If node is a version
        /// Fill RadTreeView2 with files from selected version
        /// </summary>
        void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ProductsDownLoad RadTreeView1_NodeClick BEG e.Node.Category: {0}",e.Node.Category),ModuleTraceSwitch.Sw.Info);
            RadTreeNode Node        =   null;
            // When click on product or version we reset display
            if ( e.Node.Category == "Version" )
                Node                =   e.Node;
            else
            {
                if ( e.Node.Category == "VersionDate" )
                {
                    Node            =   e.Node.ParentNode;
                }
                else if ( e.Node.Category.IndexOf("Product") > -1)
                {
                    // When clicked on a product we get first node
                    if ( e.Node.Nodes.Count > 0 )
                        Node        =   e.Node.Nodes[0];
                }
            }
            if (Node == null)
            {
                e.Node.Selected =   false;
                return;
            }
            // Select current product node and first version
            RadTreeView1.UnselectAllNodes();
            Node.Selected                   =   true;
            litWhatsNew.Text                =   Node.Attributes["WhatsNew"];
            litVersionDate.Text             =   Node.Attributes["VersionDate"];

            SqlDataReader dr                =   null;
            try
            {
                RadTreeView2.Nodes.Clear();
                int VersionProdId           =   int.Parse(Node.Value);
                int UserDownLoadId          =   int.Parse(Node.ParentNode.Attributes["UDnId"]);
                dr                          =   dwnDB.GetMainVersionFileByVersion(VersionProdId);
                while( dr.Read() )
                    AddNodeFile(dr,UserDownLoadId);
                dr.Close();
                dr                          =   dwnDB.GetNextVersionFileByVersion(VersionProdId);
                while( dr.Read() )
                    AddNodeFile(dr,UserDownLoadId);
            }
            catch(Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ProductsDownLoad RadTreeView1_NodeClick ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                if ( dr != null )
                    dr.Close();
            }
        }

        #region Std overrides 

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            //string strcult              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            RadTreeView1.AllowNodeEditing = false;
            RadTreeView2.AllowNodeEditing = false;
        }

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{
            Load                            +=  new EventHandler(Page_Load);
            RadTreeView1.NodeClick          +=  new RadTreeViewEventHandler(RadTreeView1_NodeClick);
 		}

        #endregion
    }
}